<template>
  <div :class="['my-create-task-container', !isShowFooter ? 'first' : 'second']">
    <a-modal title-align="start" :render-to-body="false" :footer="isShowFooter" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="1200">
      <template #title>
        <div v-if="!isShowFooter" class="flex-c" style="width: 100%; height: 80px; position: relative">
          <div class="wallet-con flex-c">
            <div class="img">
              <img src="https://cdn2.selleroa.com/yfni/test/1709531834135c8924b.png" alt="" />
            </div>
            <div class="text clearfix">
              <span class="fl" style="height: 28px; line-height: 28px; color: #6a4017">{{ $extract(walletInfo, 'consumeWalletAccount.userName') }}可用余额：</span>
              <span class="fl" style="color: red; font-size: 20px; color: #643910">￥{{ price }}</span>
            </div>
          </div>

          <div class="title-desc" style="margin: 0 auto; text-align: center">
            <div class="title" style="font-size: 26px">设计服务</div>
            <div style="margin-top: 10px; font-size: 14px; color: #96968d">不同服务商提供的服务和服务报价不同，请选择需要的服务内容</div>
          </div>
        </div>
        <div v-else style="font-size: 18px">确认服务</div>
      </template>

      <tabDetail :showFooter="showFooter" ref="tab" :type="type" :info="info" :walletInfo="walletInfo" :price="price" />

      <template #footer class="modal-footer">
        <div class="clearfix">
          <div class="fl">
            <span>本单任务服务费</span>
            <span style="color: red; font-size: 20px">￥{{ serviceInfo.amtQuote || 0 }}</span>
          </div>
          <div class="fr">
            <a-space>
              <a-button class="gray-outline" @click="selSubService">选择其他服务</a-button>
              <a-button type="primary" :loading="saveLoading" @click="saveOrUpdateSubmitTask">保存任务暂不发布</a-button>
              <a-button type="primary" :loading="publishTaskLoading" @click="showPublishModal">立即发布任务</a-button>
            </a-space>
          </div>
        </div>
      </template>

      <a-modal title="提示" title-align="start" v-model:visible="showPublishTaskVisiable" @ok="publishSubmitTask" @cancel="showPublishTaskVisiable = false">
        <div>发布任务需要从{{ $extract(walletInfo, 'consumeWalletAccount.userName') }}账户冻结服务费用￥{{ serviceInfo.amtQuote }}</div>
      </a-modal>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { defineComponent, ref, computed, onMounted } from 'vue'
  import { findCompanyGroupWalletByUserId } from '@/api/finance/wallet'
  import { getOrganizesUser } from '@/api/system'
  import { listTakeCompanysByTaskType, listPlatTaskConfigByParam, saveOrUpdateTask, publishTask, getTaskById, hasSkuSameService } from '@/api/task'
  import useUserStore from '@/store/modules/user'
  import tabDetail from './tabDetail.vue'
  import _ from 'lodash-es'
  import { Message, Modal } from '@arco-design/web-vue'
  const tab = ref()
  let props = defineProps(['modelValue', 'type', 'info'])
  let emits = defineEmits(['save', 'update:modelValue'])
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })

  const userInfo = useUserStore()
  let configObj: any = ref({
    SHOOT_VIDEO: '',
    NEW_PRODUCT_PICTURE: '',
    FIX_PICTURE: '',
    POSTER_SHOP_DESIGN: '',
  })
  let price = ref(0)
  let walletInfo: any = ref({})
  let serviceInfo: any = ref({})
  let isShowFooter = ref(false)
  let saveLoading = ref(false)
  let publishTaskLoading = ref(false)
  let showPublishTaskVisiable = ref(false)
  let userList: any = ref([])
  let curPage = ref('NEW_PRODUCT_PICTURE')
  let form: any = ref({
    employer: {},
    verifyerList: [],
  })

  const initWallet = async () => {
    const res: any = await findCompanyGroupWalletByUserId({ companyId: userInfo.companyId })
    walletInfo.value = res.data || {}
    let consumeWalletAccountBalance = res.data?.consumeWalletAccount?.availabeBalance || 0
    let giftWalletAccountBalance = res.data?.giftWalletAccount?.availabeBalance || 0
    price.value = consumeWalletAccountBalance + giftWalletAccountBalance
  }

  const getUserList = async () => {
    let params = {
      depart: false,
      pageNum: 1,
      pageSize: 1000,
    }
    const res: any = await getOrganizesUser(params)
    userList.value = res.data.records.map((e: any) => {
      e.name = e.userName
      return e
    })
  }

  const setEmployer = () => {
    if (props.type == 'add') {
      let obj = {
        id: userInfo.userId,
        name: userInfo.userName,
      }
      form.value.employer = _.cloneDeep(obj)
      form.value.verifyerList.push(_.cloneDeep(obj))
    }
  }

  const changeUser: any = (val: string) => {
    let item: any = userList.value.find((item: any) => item.id == val)
    if (item) {
      form.value.employer.id = item.id
      form.value.employer.name = item.name

      if (form.value.verifyerList[0].id != item.id) {
        let obj = {
          id: item.id,
          name: item.name,
        }
        form.value.verifyerList.splice(1, 1, obj)
      } else {
        form.value.verifyerList.splice(1, 1)
      }
    }
  }

  const getCompanyList = async () => {
    let params = {
      taskType: curPage.value,
      companyId: userInfo.companyId,
    }
    const res: any = await listTakeCompanysByTaskType(params)
    if (res) {
      tab.value.setServiceProviderList(res.data || [], props.info || {})
    }
  }

  const selSubService = () => {
    isShowFooter.value = false
    tab.value.resetServiceInfo()
  }

  const tabClcik = () => {
    isShowFooter.value = false
    tab.value.resetServiceInfo()
    tab.value.resetSkuInfo()
    getCompanyList()
  }

  const showFooter = (data: any) => {
    serviceInfo.value = data
    isShowFooter.value = true
  }

  const getConfigList = async () => {
    const res: any = await listPlatTaskConfigByParam({ loadAll: true })
    if (res) {
      res.data.forEach((e: any) => {
        configObj.value[e.taskType] = e.taskDesc
      })
    }
  }

  const saveOrUpdateSubmitTask = async () => {
    let tabParams = tab.value.getForm()
    if (tabParams === false) return
    let params = {
      // type: curPage.value,
      status: 'WAIT_PUBLISH',
      ...tabParams,

      amtCost: serviceInfo.value.amtQuote,
    }

    if (props.type != 'add') params.id = props.info.id

    try {
      saveLoading.value = true
      const res: any = await saveOrUpdateTask(params)
      if (res) {
        emits('save')
        Message.success('保存成功')
        showvisible.value = false
      }
    } catch (error) {}
    saveLoading.value = false
  }

  const publishSubmitTask = async () => {
    let tabParams = tab.value.getForm()
    if (tabParams === false) return
    let params = {
      // type: curPage.value,
      status: 'WAIT_PUBLISH',
      ...tabParams,

      from: userInfo.jumpFlag == 'erp' ? 'erp' : 'saas',
      amtCost: serviceInfo.value.amtQuote,
    }

    if (props.type != 'add') params.id = props.info.id

    try {
      publishTaskLoading.value = true
      const res: any = await publishTask(params)
      if (res) {
        emits('save')
        Message.success('发布成功')
        showvisible.value = false
      }
    } catch (error) {}
    publishTaskLoading.value = false
  }

  const showPublishModal = async () => {
    let tabParams = tab.value.getForm()
    if (tabParams === false) return
    if (tabParams.product.id) {
      let params = {
        serviceId: tabParams.taskRequire.id,
        sku: tabParams.product.sku,
        takeCompanyId: tabParams.takeCompany.id,
      }
      const res: any = await hasSkuSameService(params)
      if (!res.data) {
        showPublishTaskVisiable.value = true
      } else {
        Modal.info({
          title: '提示',
          content: '已存在相同服务内容的任务，是否继续发布任务',
          titleAlign: 'start',
          cancelText: '取消',
          hideCancel: false,
          onOk: () => {
            showPublishTaskVisiable.value = true
          },
        })
      }
    } else {
      showPublishTaskVisiable.value = true
    }
  }

  onMounted(() => {
    if (props.type == 'edit') {
      isShowFooter.value = true
      serviceInfo.value.amtQuote = props.info.taskRequire.amtQuote
      // getTaskDetail()
      curPage.value = props.info.type
    }
    initWallet()
    getUserList()
    setEmployer()
    // getCompanyList()
    getConfigList()
  })
</script>

<style lang="less" scoped>
  .first {
    :deep(.arco-modal) {
      background: radial-gradient(at top right, #f7eff4, #f0f2f7);
    }
    :deep(.arco-modal-header) {
      border: none !important;
      height: auto;
    }
    :deep(.arco-modal-body) {
      padding: 10px 20px;
    }
  }

  .second {
    :deep(.arco-modal-body) {
      padding: 0 20px;
    }
  }
  .my-create-task-container {
    .wallet-con {
      position: absolute;
      left: 0;
      top: 20px;
      height: 60px;

      .img {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        overflow: hidden;
        z-index: 10;
        // border: 1px dashed #d3d3d3;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .text {
        padding: 10px 20px 10px 35px;
        box-sizing: border-box;
        // width: 100%;
        // border: 1px dashed red;
        margin-left: -20px;
        border-top-right-radius: 40px;
        border-bottom-right-radius: 40px;
        background: linear-gradient(#fbefd0, #ffda83);
      }
    }
  }
</style>
